<?php
/**
 * gpa_new Description
 * @package
 * @name model_user
 * @filesource model_user.php
 * @author Meta Sanjaya
 */

class model_user extends Model
{
    /**
     * @access public
     * @method __construct
     * @param void
     * @return void
     */
    public function  __construct()
    {
        parent::__construct();
    }

    public function getUsers()
    {
        return $this->db->query("SELECT * FROM #_users a LEFT JOIN #_users_acl b ON b.user_id = a.user_id LEFT JOIN #_users_profile c ON c.user_id = a.user_id")->rows;
    }

    public function getGroups()
    {
        return $this->db->query("SELECT a.*, b.description FROM #_groups a LEFT JOIN #_groups_description b ON b.group_id = a.group_id")->rows;
    }

    public function isRegistered($username)
    {
        return(count($this->getUserBy('username', $username)));
    }

    public function isActive($username)
    {
        if($user = $this->getUserBy('username', $username)) {
            return intval($user['active']);
        }

        return false;
    }

    public function checkPass($username, $password)
    {
        $pwd = pwd_gen($this->db->escape($password), $this->db->escape($username));
        $rows = $this->db->query("SELECT user_id FROM #_users WHERE username = '".$this->db->escape($username)."' AND pwd = '$pwd'")->rows;
        //die($pwd);
        return !!count($rows);
    }

    public function getUserBy($field, $value)
    {
        $return = array();

        $rows = $this->db->query("SELECT * FROM #_users WHERE $field = '".$this->db->escape($value)."'")->rows;

        if(count($rows)) {
            $return = $rows[0];
            $uid = $return['user_id'];
            $profil = $this->db->query("SELECT * FROM #_users_profile a LEFT JOIN #_users_acl b ON b.user_id = a.user_id WHERE a.user_id = '$uid'")->rows;
            if(count($profil)) {
                $return = array_merge($profil[0], $return);
            }
        }

        return $return;
    }

    public function getGroupBy($field, $value)
    {
        $return = array();
        $rows = $this->db->query("SELECT * FROM #_groups LEFT JOIN #_groups_description USING(group_id) WHERE $field = '".$this->db->escape($value)."'")->rows;
        if(count($rows)) {
            $return = $rows[0];
        }
        return $return;
    }

    public function getAvatar($uid) {
        $return = "";
        $rows = $this->db->query("SELECT avatar FROM #_users_avatar WHERE user_id = '$uid'")->rows;
        if(count($rows)) {
            $return = $rows[0]['avatar'];
        }
        return $return;
    }

    public function setAvatar($datas) {
        if(isset($datas['tmp_name'])) {
            $uid = User::getUserId();
            $old = $this->getAvatar($uid);
            if(!empty($old)) {
                $this->db->query("DELETE FROM #_users_avatar WHERE user_id = '$uid'");
                @unlink(getImgPath() . "user/avatar/" . $old);
            }
            loadLibrary('Image', false);
            $new = time() . md5(User::getUserId()) . ".jpg";
            $real = getImgPath() . "user/avatar/$new";
            if(@move_uploaded_file($datas['tmp_name'], $real)) {
                $thumb = create_cropped_thumbnail($real, 100, getImgPath() . "user/avatar/", getImgPath() . "user/avatar/");
                if(!empty($thumb)) {
                    $this->db->query("INSERT INTO #_users_avatar SET user_id = '$uid', avatar = '$thumb'");
                    @unlink($real);
                }
            } else {
                @unlink($datas['tmp_name']);
            }
        }
    }

    public function getTools() {
        $return = array();
        $cat = $this->db->query("SELECT DISTINCT category FROM #_users_tools")->rows;
        $uid = User::getUserId();

        foreach($cat as $c) {
            $tools = $this->db->query("SELECT tool_id, tools FROM #_users_tools WHERE user_id = '$uid' AND category = '".$c['category']."'")->rows;
            foreach($tools as $t) {
                if(!isset($return[$c['category']])) {
                    $return[$c['category']] = array();
                }

                $return[$c['category']][] = $t;
            }
        }

        return $return;
    }

    public function newUser($datas)
    {
        $post = $datas['post'];
        $files = $datas['files'];

        $pwd = pwd_gen($this->db->escape($post['reg_pw1']), $this->db->escape($post['reg_username']));

        $this->db->query("INSERT INTO #_users SET username = '".$this->db->escape($post['reg_username'])."', group_id = '".(isset($post['reg_group_id'])?$post['reg_group_id']:getInstance('config')->get('default_group'))."', pwd = '$pwd', display_email = '".(isset($post['reg_display_email'])?$post['reg_display_email']:0)."'");
        $uid = $this->db->getInsertId();

        $this->db->query("INSERT INTO #_users_profile SET user_id = '$uid', name = '".$this->db->escape($post['reg_fullname'])."', nickname = '".$this->db->escape($post['reg_screenname'])."', email = '".$this->db->escape($post['reg_email'])."', url = '".$this->db->escape($post['reg_homepage'])."', city = '".$this->db->escape($post['reg_town'])."', province = '".$this->db->escape($post['reg_province'])."', country = '".$this->db->escape($post['reg_country'])."'");
        $this->db->query("INSERT INTO #_users_points SET user_id = '$uid'");

        if(isset($files['reg_idcard'])) {
            if($files['reg_idcard']['type'] == 'image/jpeg' && intval($files['reg_idcard']['size'])<307201) {
                @move_uploaded_file($files['reg_idcard']['tmp_name'], getAppImgPath('admin') . 'user/idcard/' . $uid . '.jpg');
            }
        }

        $datas['user_id'] = $uid;
        $datas['album_name'] = "Public";
        $datas['private'] = 0;

        $model_album = $this->getModel('album');
        $model_album->addAlbum($datas);

        $datas['album_name'] = "Not Selected";
        $datas['private'] = 1;

        $model_album->addAlbum($datas);

        //die($pwd);

        $username = $this->db->escape($post['reg_username']);
        $password =  $this->db->escape($post['reg_pw1']);

        if(!getInstance('config')->get('email_validation')) {
            return $this->db->query("UPDATE #_users SET active = '1' WHERE user_id = '$uid'");
        }        

        $token = md5($username.time().$password);

        $html = "<p>this email is activation email for</p><br/>";
        $html .= "<p>username: <b>$username</b></p>";
        $html .= "<p>password: <b>$password</b></p>";
        $html .= "<br/><p>please follow this link to activate your account.</p>";
        $html .= '<a href="'.getAppUrl('user', 'email_validation').'/'.$uid.'/'.$token.'/">'.getAppUrl('user', 'email_validation').'/'.$uid.'/'.$token.'/</a>';
        $html .= '<p>thank you</p>';

        Mail::sendHtml($this->db->escape($post['reg_email']), 'no-reply@' . getInstance('server')->get('HTTP_HOST'), "email validation for username: " . $username, $html);

        $this->db->query("INSERT INTO #_users_validation SET user_id = '$uid', token = '$token'");

        return true;
    }

    public function editUser($datas)
    {
        $post = $datas['post'];
        $files = $datas['files'];

        $this->db->query("UPDATE #_users SET display_email = '".(isset($post['reg_display_email'])?$post['reg_display_email']:0)."' WHERE username = '".$this->db->escape($post['reg_username'])."'");

        if(!empty($post['reg_pw1'])) {
            $pwd = pwd_gen($this->db->escape($post['reg_pw1']), $this->db->escape($post['reg_username']));
            $this->db->query("UPDATE #_users SET pwd = '$pwd' WHERE username = '".$this->db->escape($post['reg_username'])."'");
        }

        $uid = $this->db->query("SELECT user_id FROM #_users WHERE username = '".$this->db->escape($post['reg_username'])."'")->rows[0]['user_id'];

        $this->db->query("UPDATE #_users_profile SET name = '".$this->db->escape($post['reg_fullname'])."', nickname = '".$this->db->escape($post['reg_screenname'])."', email = '".$this->db->escape($post['reg_email'])."', url = '".$this->db->escape($post['reg_homepage'])."', city = '".$this->db->escape($post['reg_town'])."', province = '".$this->db->escape($post['reg_province'])."', country = '".$this->db->escape($post['reg_country'])."' WHERE user_id = '$uid'");

        User::setSession($this->getUserBy('user_id', $uid));

        if(isset($files['reg_idcard'])) {
            if($files['reg_idcard']['type'] == 'image/jpeg' && intval($files['reg_idcard']['size'])<307201) {
                return @move_uploaded_file($files['reg_idcard']['tmp_name'], getAppImgPath('admin') . 'user/idcard/' . $uid . '.jpg');
            }
        }

        return true;
    }

    public function activateUser($id) {
        return $this->db->query("UPDATE #_users SET active = '1' WHERE user_id = '$id'");
    }

    public function deactivateUser($id) {
        return $this->db->query("UPDATE #_users SET active = '0' WHERE user_id = '$id'");
    }

    public function verifyUser($id) {
        return $this->db->query("UPDATE #_users SET verified = '1' WHERE user_id = '$id'");
    }

    public function unverifyUser($id) {
        return $this->db->query("UPDATE #_users SET verified = '0' WHERE user_id = '$id'");
    }

    public function validateUser($id, $token) {
        $data = $this->db->query("SELECT * FROM #_users_validation WHERE user_id = '$id' AND token = '$token'")->rows;

        if(count($data)) {
            $this->db->query("DELETE FROM #_users_validation WHERE user_id = '$id'");
            $this->db->query("UPDATE #_users SET active = '1' WHERE user_id = '$id'");
            return true;
        }

        return false;
    }

    public function reset_pass($username, $email="") {
        $username = $this->db->escape($username);
        $pass = substr(md5(microtime()), -10);
        $pwd = pwd_gen($pass, $username);

        $this->db->query("UPDATE #_users SET pwd = '$pwd' WHERE username = '$username'");

        if(!empty($email)) {
            $html = '<p>Your password has been reset</p>';
            $html .= '<p>username: <b>'.$username.'</b></p>';
            $html .= '<p>password: <b>'.$pass.'</b></p>';
            $html .= '<p>please login using that password and then you can change it in edit profile. Thank You.</p>';
            
            @Mail::sendHtml($email, 'no-reply@' . getInstance('server')->get('HTTP_HOST'), "New Password for username: $username", $html);
        }

        return $pass;
    }

    public function forget_pwd($email) {
        $email = $this->db->escape($email);
        $rows = $this->db->query("SELECT a.username FROM #_users a LEFT JOIN #_users_profile b ON b.user_id = a.user_id WHERE b.email = '$email'")->rows;
        if(!count($rows)) {
            return false;
        }

        return $this->reset_pass($rows[0]['username'], $email);
    }
}
?>